//获取页面的3个按钮
var vgaButton = document.querySelector("button#vga");
var qvgaButton = document.querySelector("button#qvga");
var hdButton = document.querySelector("button#hd");
// 获取视屏显示区域
video = document.querySelector("video");
//采集到的视频流
var stream;
//兼容不同浏览器调用摄像头
navigator.getUserMedia = navigator.getUserMedia ||
  navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
// 调用成功后回调函数
function successCallback(gotStream) {
  //设置流
  window.stream = gotStream;

   //将获取到的流展示在页面上
   video.srcObject = stream;
  //播放视屏画面
  video.play();
}
// 获取摄像头失败回调函数
function errorCallback(error){
  console.log("navigator.getUserMedia error: ", error);
}
// 低分辨率约束
var qvgaConstraints = {
  video: {
    mandatory: {
      maxWidth: 320,
      maxHeight: 240
    }
  }
};
// 标准分辨率视频的约束对象
var vgaConstraints = {
  video: {
    mandatory: {
      maxWidth: 640,
      maxHeight: 480
    }
  }
};
// 高分辨率视频的约束对象
var hdConstraints = {
  video: {
    mandatory: {
      minWidth: 1280,
      minHeight: 960
    }
  }
};
// 点击事件
qvgaButton.onclick = function() {
  getMedia(qvgaConstraints)
};
vgaButton.onclick = function() {
  getMedia(vgaConstraints)
};
hdButton.onclick = function() {
  getMedia(hdConstraints)
};

//设置约束参数
function getMedia(constraints) {
  if (!!stream) {
    video.src = null;
    stream.stop();
  }
  navigator.getUserMedia(constraints, successCallback, errorCallback);
}